package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.schedule.IScheduleClient;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.TaskTypeEnum;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;


@Slf4j
@Service
public class WmNewsTaskServiceImpl implements WmNewsTaskService {

    @Autowired
    private IScheduleClient scheduleClient;

    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    /**
     * 添加任务到延迟队列中
     *
     * @param wmNews
     */
    @Override
    public void addWmNewsToTask(WmNews wmNews) {
        log.info("添加任务到延迟服务中----begin");

        // 初始化Task对象
        Task task = new Task();
        task.setExecuteTime(wmNews.getPublishTime().getTime());
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());

        // 创建新的文章对象,封装文章的id
        WmNews wmNewsTask = new WmNews();
        wmNewsTask.setId(wmNews.getId());
        // 序列换传输的对象
        task.setParameters(ProtostuffUtil.serialize(wmNewsTask));

        // 添加任务
        scheduleClient.addTask(task);

        log.info("添加任务到延迟服务中----end");
    }

    /**
     * 消费延迟队列数据
     */
    @Override
    @Scheduled(fixedRate = 10000)
    public void scanNewsByTask() throws Exception {
        // 调用接口获取任务
        ResponseResult result = scheduleClient
                .poll(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(),
                        TaskTypeEnum.NEWS_SCAN_TIME.getPriority());

        if (result != null && result.getCode() == 200 && result.getData() != null) {
            log.info("获取到文章审核任务,消费任务执行---start");

            // 获取数据
            String json = JSON.toJSONString(result.getData());
            Task task = JSON.parseObject(json, Task.class);

            // 反序列化
            WmNews wmNews = ProtostuffUtil.deserialize(task.getParameters(), WmNews.class);

            // 调用审核方法
            wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
        }

        log.info("文章审核---消费任务执行---end---");
    }
}
